package com.zrrd.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.zrrd.reggie.common.BaseContext;
import com.zrrd.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求对象
        HttpServletRequest req = (HttpServletRequest) request;
        //获取响应对象
        HttpServletResponse resp = (HttpServletResponse) response;
        //通过请求对象获取本次请求过来的地址
        String requestURI = req.getRequestURI();
        System.out.println("拦截到的请求地址====>" + requestURI);
        //定义不需要拦截的请求地址
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断当前请求路径是否需要处理
        boolean check = this.check(urls, requestURI);
        //如果Id存在代表登陆了
        if (check) {
            //放行
            chain.doFilter(req, response);
            return;
        }

        //从Session中获取登录时存入的员工Id
        Long empId = (Long) req.getSession().getAttribute("empId");
        //如果Id存在   代表登陆了
        if (empId != null) {
            //如果已经登录  将当前员工的id存入到线程变量中
            BaseContext.setCurrentId(empId);
            //放行
            chain.doFilter(req, response);
            return;
        }

        //从Session中获取登录时存入的用户Id
        Long userId = (Long) req.getSession().getAttribute("userId");
        //如果Id存在   代表登陆了
        if (userId != null) {
            //如果已经登录  将当前用户的id存入到线程变量中
            BaseContext.setCurrentId(userId);
            //放行
            chain.doFilter(req, response);
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    //判断路径是否匹配方法
    private boolean check(String[] urls, String requestUrl) {
        //遍历数组
        for (String url : urls) {
            //判断是否匹配
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match) {
                return match;
            }
        }
        return false;
    }
}
